<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-12
 * Time: 19:49
 */

namespace app\service;


use app\model\ChatmsgModel;
use app\common\model\ChatMsg;
use app\common\model\User as UserModel;
use app\common\model\WechatTmplLog as WechatTmplLogModel;

use think\Db;
use think\Exception;

class MsgService extends ThirdService
{
    public $chatMsgModel;
    public $mallTmplModel;//商城模版
    public $tmplModel;//模版模型


    //模版消息类型
    public static $tempType_FEN_XIAO = 'FEN_XIAO'; //分销
    public static $tempType_DENG_JI = 'DENG_JI';//等级变更
    public static $tempType_FA_HUO = 'FA_HUO'; //发货
    public static $tempType_TUIHUO_APPLY = 'TUIHUO_APPLY'; //提货
    public static $tempType_TUIHUO_RES = 'TUIHUO_RES'; //提现申请
    public static $tempType_TIXIAN_OK = 'TIXIAN_OK'; //提现成功
    public static $tempType_TIXIAN_TIJIAO = 'TIXIAN_TIJIAO'; //提现提交
    public static $tempType_CZ_OK = 'CZ_OK'; //充值成功
    public static $tempType_YUE = 'YUE'; //账户余额
    public static $tempType_KH_MSG = 'KH_MSG'; //客户请求通知
    public static $tempType_NEW_USER = 'NEW_USER'; //注册审核通知
    public static $tempType_NEW_WITHDRAW = 'NEW_WITHDRAW'; //提现申请通知

    public static $tempType_NEW_USER_FANGWEN = 'USER_FANGWEN'; //用户访问
    public static $tempType_NEW_CARDVISITED = 'NEW_CARDVISITED'; //用户访问名片通知
    public static $tempType_NEW_ORDER = 'NEW_ORDER'; //新订单生成提醒
    public static $tempType_NEW_GAME = 'NEW_GAME'; //赛事安排通知
    public static $tempType_NEW_COURSE_REGISTER = 'NEW_COURSE'; //约课成功提醒
    public static $tempType_ACTIVE = 'ACTIVE'; //报名成功通知


    //构造函数
    public function __construct($option = false)
    {
        parent::__construct($option);
        $this->chatMsgModel = new ChatmsgModel();//new ChatMsg();//Db::name('chat_msg');//('chat_msg');
        $this->mallTmplModel = Db::name('wechat_tmpl');
        $this->tmplModel = Db::name('wechat_tmpl_model');
    }

    /**
     * 查询用户
     * @param $id
     * @param int $page
     * @param int $page_num
     * @return array|bool
     */
    public function queryListById($uid, $id, $page = 1, $page_num = 20)
    {
        try {
            /* $where=[
                'revoke' => 0,
                'status' => 1,
                'mall_id' => config('mall_id'),
            ];
            if($id>0){
                $where['id']=array('lt',$id);
            } */
            $group_id = UserModel::getGroupId($uid);
            $mall_id = config('mall_id');
            $where = "`revoke`=0 and `status`=1 and `mall_id`={$mall_id}";
            if ($id > 0) {
                $where .= " and id<{$id}";
            }
            $where .= " and (group_id='{$group_id}' or (type in ('seeGoods','buy')))";
            return ChatMsg::getPage($where, $page, $page_num, 'id desc');
        } catch (Exception $ex) {
            LogService::S()->writeLog('Exception', 'MsgService/queryListById', $ex->getMessage());
            return false;
        }

    }


    //模版设置模版消息
    public function resetMallTmpl($mall_id)
    {
        try {
            //LogService::S()->writeLog("data","dt", $this->officialAccount);
            //开通模板消息
            $this->officialAccount->template_message->setIndustry(1, 2);
            $this->mallTmplModel->where('mall_id', $mall_id)->delete(); //重新获取所有模版消息
            $tmplmodelList = $this->tmplModel->field('title,tmp_name,bianhao')->select()->toArray();
            $addArray = array();

            //先删除模版
            $re = $this->officialAccount->template_message->getPrivateTemplates();
            $re = $re['template_list'];

            foreach ($re as $rk => $rv) {
                $this->officialAccount->template_message->deletePrivateTemplate($rv['template_id']);
            }

            foreach ($tmplmodelList as $k => $v) {
                $addArray[$k]['tmpl_name'] = $v['tmp_name'];
                $temp_info = $this->officialAccount->template_message->addTemplate($v['bianhao']);
                $addArray[$k]['tmpl_id'] = $temp_info['template_id'];
                $addArray[$k]['mall_id'] = $mall_id;
                $addArray[$k]['title'] = $v['title'];
                $addArray[$k]['create_time'] = date('Y-m-d H:i:s');
            }
            //dump($this->officialAccount->template_message->getPrivateTemplates());
            return $this->mallTmplModel->insertAll($addArray);
        } catch (Exception $ex) {
            echo $ex->getMessage();
            die;
        }
    }


    /**
     * 发送模版消息
     * @param $temp_type
     * @param $mall_id
     * @param $uid
     * @param array $data
     * @param string $url
     * @return array|bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function sendTemp($temp_type, $mall_id, $uid, $data = array(), $url = '')
    {
        try {
            $opneid = UserService::S()->getWechatUserFiled(array('uid' => $uid, 'mall_id' => $mall_id), 'openid'); //查询出用户openid
            if (!$opneid) {
                return array('code' => 202, '用户ID未查询到信息');
            }
            $template_info = $this->mallTmplModel
                ->field('color,tmpl_id')
                ->where(array('mall_id' => $mall_id, 'tmpl_name' => $temp_type))
                ->find(); //获取模版ID
            // dump($this->mallTmplModel->getLastSql());die;
            $color = $template_info['color'];
            $sendData['touser'] = $opneid;
            $sendData['template_id'] = $template_info['tmpl_id'];
            $sendData['url'] = $url;
            $sendData['data'] = self::backTempDataByType($temp_type, $data, $color);//发送数据
            if (empty($sendData['data'])) {
                return array('code' => 202, '发送数据为空,请检查类型是否正确');
            }
            $log = WechatTmplLogModel::create([
                'mall_id' => $mall_id,
                'uid' => $uid,
                'content' => json_encode($sendData, JSON_UNESCAPED_UNICODE),
            ]);
            return true;
        } catch (Exception $ex) {
            LogService::S()->writeLog('Exception', $ex->getMessage());
            return false;
        }

    }

    /* 发送单条模板消息 */
    public function send($log)
    {
        $res = $this->officialAccount->template_message->send(json_decode($log['content'], true));
        //发送模板消息请求
        if ($res['errcode'] == 0) {
            WechatTmplLogModel::where('id', $log['id'])->update([
                'status' => 1,
                'result' => json_encode($res, JSON_UNESCAPED_UNICODE)
            ]);
        } else {
            WechatTmplLogModel::where('id', $log['id'])->update([
                'status' => 2,
                'result' => json_encode($res, JSON_UNESCAPED_UNICODE)
            ]);
        }
        return $res;
    }


    /**
     * 返回模版消息数组
     * @param $temp_type
     * @param $data
     * @param $color
     * @return array
     */
    public function backTempDataByType($temp_type, $data, $color)
    {
        $back_data = array();
        switch ($temp_type) {
            case self::$tempType_KH_MSG: //客户请求通知
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['user_name'],//用户名称
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['mobile'], //用户手机号码
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //用户备注
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_YUE: //账户余额通知
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['user_name'],//用户名称
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['money'], //账户余额
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => date('Y-m-d H:i:s'),
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'],
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_CZ_OK: //充值成功通知
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['money'],//充值金额
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['create_time'], //充值时间
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => date('sum_money'), //账户余额
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'],
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_TIXIAN_TIJIAO: //提交提现
            case self::$tempType_TIXIAN_OK: //提现成功通知
                $data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['money'],//提现金额
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['timet'], //提现时间
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'],
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_FA_HUO: //订单发货提醒
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['order_sn'],//订单编号
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['express'], //快递公司
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => $data['express_no'], //快递单号
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //订单备注
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_DENG_JI: //会员等级变更通知
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['now_grade'],//当前等级
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['prv_grade'], //上一个等级
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //备注信息
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_NEW_USER: //新用户给上级发消息
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['nickname'],//会员帐号
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => date('Y-m-d H:i:s'), //注册时间
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //备注信息
                        'color' => $color,
                    )
                );
                break;

            case self::$tempType_NEW_CARDVISITED: //用户访问名片通知
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => date('Y-m-d H:i:s'),//姓名
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => '名片被查看', //触发类型
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => $data['nickname'] . '查看了您的名片', //触发详情
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //备注信息
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_NEW_USER_FANGWEN://用户访问
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['nickname'],//会员帐号
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['project'], //,date('Y-m-d H:i:s'), //访问项目
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => $data['ziyuan'],//date('Y-m-d H:i:s'), //注册时间
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //备注信息
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_NEW_ORDER://新订单生成提醒
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['time'],//时间
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['name'], //,date('Y-m-d H:i:s'), //商品名称
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => $data['order_sn'],//date('Y-m-d H:i:s'), //订单号
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //备注信息
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_NEW_GAME://赛事安排通知
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['name'] . '（赛事编号：'.$data['id'].'）',//赛事名称
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['start_time'] . '至' . $data['end_time'],  //比赛时间
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => '1支球队', //比赛人数
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //备注信息
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_NEW_COURSE_REGISTER://约课成功提醒
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['course'] . '（课程编号：'.$data['course_id'].'）',//赛事名称
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['name'],  //队员
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => date('Y-m-d H:i:s',$data['create_time']), //时间
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //备注信息
                        'color' => $color,
                    )
                );
                break;
            case self::$tempType_ACTIVE://约课成功提醒
                $back_data = array(
                    'first' => array(
                        'value' => $data['first'],
                        'color' => $color
                    ),
                    'keyword1' => array(
                        'value' => $data['keyword1'] ,//参与者
                        'color' => $color,
                    ),
                    'keyword2' => array(
                        'value' => $data['keyword2'],  //活动名称
                        'color' => $color,
                    ),
                    'keyword3' => array(
                        'value' => $data['keyword3'], //时间
                        'color' => $color,
                    ),
                    'remark' => array(
                        'value' => $data['remark'], //备注信息
                        'color' => $color,
                    )
                );
                break;
        }

        return $back_data;
    }

}